﻿using System.Collections.Generic;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using SpecFlowTfsLinker.Entities;
using SpecFlowTfsLinker.Parser;

namespace SpecFlowTfsConnector
{
    public class TfsSpecFlowConnector
    {
        public TfsConnector Connector { get; private set; }

        public TfsSpecFlowConnector()
        {
            Connector = new TfsConnector();
        }

        public List<UserStory> GetUserStories(string projectName)
        {
            var userStories = new List<UserStory>();
            var usCollection = Connector.GetTfsUserStoriesWorkItem(projectName);
            var builder = UserStory.Builder;
            GetUserStory(usCollection, builder, userStories);
            return userStories;
        }

        private static void GetUserStory(WorkItemCollection usCollection, UserStory.UsBuilder builder,
                                         ICollection<UserStory> userStories)
        {
            foreach (WorkItem us in usCollection)
            {
                builder.Id(us.Id);
                builder.Title(us.Title);
                builder.Description(us.Description);
                GetTestCases(builder, us);
                userStories.Add(builder.Build());
            }
        }

        private static void GetTestCases(UserStory.UsBuilder builder, WorkItem us)
        {
            foreach (var testCase in TfsConnector.GetTestsCaseWorkItemByUserStory(us))
            {
                builder.AddTestCase(TestCaseParser.Create(testCase.Title, testCase.Description));
            }
        }
    }
}